#!/usr/local/bin/python
# -*- coding: utf-8 -*-



from sqlalchemy import Column, Integer, Float, and_, Text, or_
from sqlalchemy.orm import declarative_base
import hashlib

import init
from init import session
from initLogger import logger
from internal import saltText

Base = declarative_base()

class UserInforAlchemy(Base):
    '''
    类功能：用户信息表
    '''
    __tablename__="user_infor"

    id = Column(Integer, primary_key=True, autoincrement=True, comment="")
    user_name = Column(Text, comment="用户名称")
    user_id = Column(Text, comment="用户id")
    group_name = Column(Text, comment="用户组名称")
    group_id = Column(Text, comment="用户组id")
    password_md5 =  Column(Text, comment="用户密码md5")


    def __init__(self,
                 userName="userName",
                 userId="",
                 groupName="groupName",
                 groupId="",
                 passwordText=""):
        self.user_name = userName
        self.user_id = userId
        self.group_name= groupName
        self.group_id = groupId

        fullPasswordText=saltText+passwordText

        hash_object = hashlib.sha3_512(fullPasswordText.encode('utf-8'))
        hexdigest = hash_object.hexdigest()
        self.password_md5 = hexdigest



    def AddUserInforItem(self):
        '''
        函数功能：添加一条用户信息
        :return:
        '''
        logger.debug("call AddUserInforItem function")
        session.add(self)
        session.commit()

    def verifyPassword(self, userName, passwordText):
        '''
        函数功能：验证登录账号密码信息
        :param userName:
        :param password:
        :return: boolean
            True：认证失败
            False：认证失败
        '''
        logger.debug("call verifyPassword function")

        fullPasswordText=saltText+passwordText

        hash_object = hashlib.sha3_512(fullPasswordText.encode('utf-8'))
        hexdigest = hash_object.hexdigest()

        result = session.query(UserInforAlchemy)\
                                      .filter(and_(UserInforAlchemy.user_name == userName,
                                                    UserInforAlchemy.password_md5 == hexdigest)) \
                                      .all()
        if len(result)>0:
            logger.info("login successful!")
            return True
        else:
            logger.info("login failed!")
            return False



def main():
    '''
    函数功能：

    :return:
    '''
    '''
    userInforAlchemy = UserInforAlchemy(userName ="anbc",
                                        userId="0001",
                                        groupName="anbc_family",
                                        groupId="0001",
                                        passwordText="")

    userInforAlchemy.AddUserInforItem()
    '''

    userInforAlchemy = UserInforAlchemy()
    result = userInforAlchemy.verifyPassword("anbc", "")
    logger.info(result)





# 创建数据库表
UserInforAlchemy.metadata.create_all(init.engine)

if __name__ == '__main__':
    main()